import React, {useEffect, useMemo, useState} from "react";
import { View, Text } from "@tarojs/components";
import Page from "@/components/page";
import PageNav from "@/components/pageNav";
import moment from "moment";
import Taro, { useLoad, useReachBottom, usePullDownRefresh, useDidShow, getStorageSync, setStorageSync } from "@tarojs/taro";
import account from "@/store/account";
import http from "@/request";
import {billType} from "@/types";
import BillList from "@/components/billList";
import BillForm from "@/components/billForm";
import viewMode from "@/store/viewMode";
import {HideLoading, ShowLoading, ShowToast, VibrateShort} from "@/utils";
import { eventBus } from "@/event-bus";
import BillFilter from "@/pages/bills/billFilter";
import "./index.scss"
import {MoneyFormat} from "@/utils/format";

interface filterType {
    startDate?: string,
    endDate?: string,
    note?: string,
    type?: number,
    userId?: number,
    userName?: string,
    categoryId?: number,
    categoryName?: string
}

const pageConfig = {
    page: 1,
    size: 10
}

const initData = {
    startDate: moment().startOf('month').format('YYYY-MM-DD'),
    endDate: moment().format('YYYY-MM-DD')
}

const Bills: React.FC = () => {
    const [month, setMonth] = useState<string>('')
    const [formVisible, setFormVisible] = useState<boolean>(false)
    const [bills, setBills] = useState<(billType & { id: number, category: number })[]>([])
    const [bill, setBill] = useState<billType & { id: number, category: number }>()
    const [total, setTotal] = useState(0)
    const [isNoMore, setIsNoMore] = useState('')
    const [filterVisible, setFilterVisible] = useState(false)
    const [filterData, setFilterData ] = useState<filterType>({
        ...initData
    })
    const [headerHeight, setHeaderHeight] = useState(83)
    const [summary, setSummary] = useState({
        income: 0,
        expense: 0,
        balance: 0
    })

    const hasFilter = useMemo(() => {
        return JSON.stringify(filterData) !== JSON.stringify(initData)
    }, [filterData])

    usePullDownRefresh(() => {
        refresh()
        setTimeout(() => {
            Taro.stopPullDownRefresh();
        }, 500)
    })

    const initList = (filter?: filterType) => {
        pageConfig.page = 1
        queryBillList(true, filter)
    }

    useReachBottom(() => {
        const { page, size } = pageConfig
        if (page * size < total) {
            pageConfig.page++
            queryBillList(false)
        }
    })

    const queryBillList = (isInit: boolean, filter?: filterType) => {
        if (!month) return
        setIsNoMore('上划加载更多')
        setTotal(0)
        const {categoryId, type, startDate, endDate, note, userId} = filter || filterData
        const params = {
            ...pageConfig,
            accountId: account.activeAccount?.id,
            type,
            categorys: categoryId && [categoryId],
            startDate,
            endDate,
            note,
            userId
        }
        ShowLoading()
        http.post('/bills/page', params).then(res => {
            const summaryList = res.data.summary || []
            setSummary(summaryList.reduce((sum, item) => {
                sum.income += (item.income || 0)
                sum.expense += (item.expense || 0)
                sum.balance += (item.balance || 0)
                return sum
            }, {
                income: 0,
                expense: 0,
                balance: 0
            }))
            if (isInit) {
                setBills(res.data.records || [])
            } else {
                setBills(prevBills => [...prevBills, ...(res.data.records || [])])
            }
            setTotal(res.data.total || 0)
            const { page, size } = pageConfig
            if (page * size < res.data.total) {
                setIsNoMore('上划加载更多')
            } else {
                setIsNoMore('没有更多了')
            }
            HideLoading()
        }).catch(err => {
            ShowToast(err.msg || '获取数据失败')
        })
    }

    const closeModal = () => {
        setFormVisible(false)
    }
    const openEdit = (item) => {
        setBill(item)
        setFormVisible(true)
    }
    const refresh = () => {
        closeModal()
        initList()
    }

    useDidShow(() => {
        const needRefresh = !!getStorageSync('bill-list-refresh')        
        if (needRefresh) {
            refresh()
            setStorageSync('bill-list-refresh', '')
        }
    })

    useLoad((parms) => {
        setMonth(moment(parms.month).format('YYYY-MM'))
        eventBus.on('refreshBillListEvent', () => {
            setStorageSync('bill-list-refresh', true)
        });
    })
    useEffect(() => {
        viewMode.setBehind(formVisible)
    }, [formVisible])

    useEffect(() => {
        initList()
    }, [month])
    
    const deleteBill = (bill) => {
        Taro.showModal({
            title: '是否删除所选账单？',
            content: '',
            success: (res: any) => {
                if (res.confirm) {
                    http.delete(`/bills/delete/${bill.id}`).then(() => {
                        ShowToast("删除成功")
                        refresh()
                    }).catch(err => {
                        ShowToast(err.msg || '删除失败')
                    })
                }
            }
        })
    }

    return (
        <Page className="page-background bills-page text-main-color flex-column flex-item">
            <PageNav showBack getHeight={setHeaderHeight} className="count-page-header page-background need-filter">
                <View className={`filter-btn ${hasFilter ? 'has-filter' : ''}`} onClick={() => {
                    VibrateShort()
                    setFilterVisible(true)
                }}>
                    <Text>筛选账单</Text>
                    <Text className="iconfont icon-base-down"></Text>
                </View>
            </PageNav>
            <View style={{marginTop: headerHeight + 'px'}} className="page-body need-filter flex-column flex-item flex1">
                <View className="summary-container card-background">
                    <View className="title">数据统计（{hasFilter ? '自定义筛选' : '默认本月'}）</View>
                    <View className="summary-row flex-row">
                        <View className="summary-row-item flex-row flex1">
                            <View className="label">支出</View>
                            <View className="value font-size36">{MoneyFormat(summary.expense)}</View>
                        </View>
                        <View className="summary-row-item flex-row flex1">
                            <View className="label">收入</View>
                            <View className="value font-size36">{MoneyFormat(summary.income)}</View>
                        </View>
                    </View>
                    <View className="summary-row flex-row">
                        <View className="summary-row-item flex-row flex1">
                            <View className="label">结余</View>
                            <View className="value font-size36">{MoneyFormat(summary.balance)}</View>
                        </View>
                        <View className="flex1"></View>
                    </View>
                </View>
                <BillList
                    className="bill-list-container"
                    title={`查询到${total}条数据`}
                    bills={bills}
                    onDelete={deleteBill}
                    onEdit={openEdit}>
                </BillList>
                <View className="is-end">{isNoMore}</View>
            </View>
            <BillForm
                visible={formVisible}
                onClose={closeModal}
                onSure={refresh}
                bill={bill}>
            </BillForm>
            <BillFilter
                show={filterVisible}
                data={filterData}
                onClose={() => setFilterVisible(false)}
                onConfirm={(val) => {
                    setFilterVisible(false)
                    setFilterData({...val})
                    initList(val)
                }}
            ></BillFilter>
        </Page>
    )
}

export default Bills